package com.ygg.bootservice.config;

import com.alibaba.druid.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ygg.bootcommon.config.NotIntercept;
import com.ygg.bootcommon.config.RequestUtils;
import com.ygg.bootcommon.model.dao.InterfaceLogDao;
import com.ygg.bootcommon.model.entity.InterfaceLog;
import com.ygg.bootcommon.utils.CommonUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：longyang
 * @date ：Created in 2020/12/18 16:51
 * @description：
 * @modified By：
 * @version: $
 */
@Aspect
@Component
@Transactional
public class TimeAspect {

    @Autowired
    private InterfaceLogDao interfaceLogDao;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    //切入点
    @Around("execution(* com.ygg.bootservice.controller.*.*(..))")
    //增强
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        Gson gson = new GsonBuilder().serializeNulls().create();
        HttpServletRequest request = RequestUtils.getHttpServletRequest();
        String url = request.getRequestURI();//请求url
        String className = pjp.getTarget().getClass().getName();//请求接口类名
        String methodName = pjp.getSignature().getName();//方法名
        Class tClass = Class.forName(className);
        Method[] methods = tClass.getMethods();
        boolean flag = true;
        for(Method m : methods){
            if(methodName.equals(m.getName())){
                if(m.isAnnotationPresent(NotIntercept.class)){
                    //类上配置了NotIntercept注解！
                    //有注解，则直接通过，不写入数据库
                    flag = false;
                    break;
                }
            }
        }
        InterfaceLog requestInterfaceLog = new InterfaceLog();
        Object[] args = pjp.getArgs();
        for (Object arg :args){
            String requestParams = gson.toJson(arg);
            requestInterfaceLog.setRequestParams(requestParams);
        }

        if(flag){
            boolean isJson = CommonUtils.isJson(requestInterfaceLog.getRequestParams());
            Map<String,String> map = null;
            if(isJson){
                map = gson.fromJson(requestInterfaceLog.getRequestParams(), HashMap.class);
            }
            requestInterfaceLog.setClassName(className);
            requestInterfaceLog.setMethodName(methodName);
            requestInterfaceLog.setUrl(url);
            if(map == null || StringUtils.isEmpty(map.get("userId"))){
                requestInterfaceLog.setCreateId("SYSTEM");
                requestInterfaceLog.setModifyId("SYSTEM");
            }else{
                requestInterfaceLog.setCreateId(map.get("userId"));
                requestInterfaceLog.setModifyId(map.get("userId"));
            }
            if(map != null && !StringUtils.isEmpty(map.get("siteCode"))){
                requestInterfaceLog.setSiteCode(map.get("siteCode"));
            }
            if(map != null && !StringUtils.isEmpty(map.get("workCenterCode"))){
                requestInterfaceLog.setWorkCenterCode(map.get("workCenterCode"));
            }
            requestInterfaceLog.setCreateDate(new Date());
            requestInterfaceLog.setModifyDate(new Date());
            interfaceLogDao.insertInterfaceLog(requestInterfaceLog);//请求时保存
        }
        long start = System.currentTimeMillis();
        //调用被拦截的方法
        Object object = pjp.proceed();
        String returnParams = gson.toJson(object.toString());
        if(flag){
            boolean isJson = CommonUtils.isJson(requestInterfaceLog.getRequestParams());
            Map<String,String> map = null;
            if(isJson){
                map = gson.fromJson(requestInterfaceLog.getRequestParams(), HashMap.class);
            }
            InterfaceLog returnInterfaceLog = new InterfaceLog();
            returnInterfaceLog.setClassName(className);
            returnInterfaceLog.setMethodName(methodName);
            returnInterfaceLog.setCreateDate(new Date());
            returnInterfaceLog.setModifyDate(new Date());
            returnInterfaceLog.setUrl(url);
            returnInterfaceLog.setReturnParams(returnParams);
            if(map == null || StringUtils.isEmpty(map.get("userId"))){
                returnInterfaceLog.setCreateId("SYSTEM");
                returnInterfaceLog.setModifyId("SYSTEM");
            }else{
                returnInterfaceLog.setCreateId(map.get("userId"));
                returnInterfaceLog.setModifyId(map.get("userId"));
            }
            if(map != null && !StringUtils.isEmpty(map.get("siteCode"))){
                returnInterfaceLog.setSiteCode(map.get("siteCode"));
            }
            if(map != null && !StringUtils.isEmpty(map.get("workCenterCode"))){
                returnInterfaceLog.setWorkCenterCode(map.get("workCenterCode"));
            }
            interfaceLogDao.insertInterfaceLog(returnInterfaceLog);//返回结果时保存
        }
        return object;
    }


}
